package com.zjw.touchscreen;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.widget.*;
import androidx.annotation.RequiresApi;
import android.os.Bundle;
import com.zjw.touchscreen.config.RetrofitManager;
import com.zjw.touchscreen.http.ApiInterface;
import com.zjw.touchscreen.http.HttpStatus;
import com.zjw.touchscreen.http.entity.CaptchaImageRespVO;
import com.zjw.touchscreen.listener.RegisterListener;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.Base64;

public class RegisterActivity extends Activity {

    private ImageView captchaCodeImage;
    private TextView captchaCodeUuid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        EditText userName = findViewById(R.id.userName);
        EditText password = findViewById(R.id.password);
        EditText captchaCode = findViewById(R.id.captchaCode);
        captchaCodeImage = findViewById(R.id.captchaCodeImage);
        captchaCodeUuid = findViewById(R.id.captchaCodeUuid);
        setCaptchaCodeImage(captchaCodeImage, captchaCodeUuid);
        captchaCodeImage.setOnClickListener(v -> setCaptchaCodeImage(captchaCodeImage, captchaCodeUuid));
        Button registerButton = findViewById(R.id.btnRegister);
        registerButton.setOnClickListener(new RegisterListener(this, userName, password, captchaCode, captchaCodeUuid));
    }

    public void refreshCaptchaCodeImage(){
        setCaptchaCodeImage(captchaCodeImage, captchaCodeUuid);
    }

    private void setCaptchaCodeImage(ImageView captchaCodeImage, TextView captchaCodeUuid) {
        ApiInterface apiInterface = RetrofitManager.create(ApiInterface.class);
        Call<CaptchaImageRespVO> ajaxResultCall = apiInterface.captchaImage();
        ajaxResultCall.enqueue(new Callback<CaptchaImageRespVO>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(Call<CaptchaImageRespVO> call, Response<CaptchaImageRespVO> response) {
                CaptchaImageRespVO body = response.body();
                if (HttpStatus.SUCCESS != response.code()) {
                    Toast.makeText(getApplicationContext(), "获取验证码图片失败!", Toast.LENGTH_SHORT).show();
                    return;
                }
                String uuid = body.getUuid();
                String imgStr = body.getImg();
                byte[] imageData = Base64.getDecoder().decode(imgStr);
                captchaCodeUuid.setText(uuid);
                captchaCodeImage.setImageBitmap(BitmapFactory.decodeByteArray(imageData, 0, imageData.length));
            }

            @Override
            public void onFailure(Call<CaptchaImageRespVO> call, Throwable throwable) {
                Toast.makeText(getApplicationContext(), "获取验证码图片失败!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}